package com.qf.myshop.dao.impl;

import com.qf.myshop.dao.UserDAO;
import com.qf.myshop.entity.User;
import com.qf.myshop.utils.DruidUtils;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * dao层实现类
 * add注册/添加
 * update 修改 根据激活码更改状态
 * find 根据姓名查询
 * @author DELL
 */
public class UserDAOImpl implements UserDAO {
    private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
    private Map<String, String> map = new HashMap<>();
    {
        map.put("u_id","uid");
        map.put("u_name","username");
        map.put("u_password","upassword");
        map.put("u_email","email");
        map.put("u_sex","usex");
        map.put("u_status","ustatus");
        map.put(" u_code","code");
        map.put("u_role","urole");
    }
    @Override
    public User add(User user) {
        String sql = "insert into user values(null,?,?,?,?,?,?,?)";
        try {
            int update = queryRunner.update(sql, user.getUsername(),user.getUpassword(),user.getEmail(),user.getUsex(),user.getUstatus(),user.getCode(),user.getUrole());
            if (update>0){
                sql = "select last_insert_id()";
                BigInteger bi = queryRunner.query(sql, new ScalarHandler<>());
                System.out.println(bi);
                user.setUid(bi.intValue());
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User update(User user) {
        String sql = "update user set u_status = ? where u_code = ?  ";
        try {
            int update = queryRunner.update(sql, user.getUstatus(), user.getCode());
            if (update > 0 ){
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User find(String name) {
        String sql = "select * from user where u_name = ?";
        try {
            return queryRunner.query(sql,new BeanHandler<User>(User.class,new BasicRowProcessor(new BeanProcessor(map))),name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        UserDAO dao = new UserDAOImpl();
        User user = new User();

        user.setUstatus(1);
        user.setCode("cewewewe");
        User add = dao.update(user);
        System.out.println(add);

    }
}
